"""Agent配置路由"""
from fastapi import APIRouter, Depends, HTTPException, Body
from sqlalchemy.orm import Session
from typing import List, Dict, Any
import json
import uuid

from database import get_db
from model.models import AgentConfig, ToolConfig
from module.agent_manager import reload_agent, TOOL_MAP

router = APIRouter(prefix="/api/agent-config", tags=["Agent Config"])

@router.get("/tools")
def get_available_tools(db: Session = Depends(get_db)):
    """获取所有可用工具（从数据库）"""
    tools = db.query(ToolConfig).filter(ToolConfig.is_enabled == True).order_by(ToolConfig.category, ToolConfig.sort_order).all()
    return [t.to_dict() for t in tools]

@router.get("", response_model=List[Dict[str, Any]])
def get_configs(db: Session = Depends(get_db)):
    """获取所有 Agent 配置"""
    configs = db.query(AgentConfig).order_by(AgentConfig.updated_at.desc()).all()
    return [c.to_dict() for c in configs]

@router.post("", response_model=Dict[str, Any])
def create_config(config: Dict[str, Any], db: Session = Depends(get_db)):
    """创建新配置"""
    # 验证必填字段
    if not config.get("name"):
        raise HTTPException(status_code=400, detail="名称不能为空")
    if not config.get("system_prompt"):
        raise HTTPException(status_code=400, detail="系统提示词不能为空")
    
    # 检查名称唯一性
    existing = db.query(AgentConfig).filter(AgentConfig.name == config.get("name")).first()
    if existing:
        raise HTTPException(status_code=400, detail="该名称已存在")
        
    new_config = AgentConfig(
        id=str(uuid.uuid4()),
        name=config.get("name"),
        description=config.get("description", ""),
        system_prompt=config.get("system_prompt"),
        model=config.get("model", "claude-3-5-sonnet-20241022"),
        agent_type=config.get("agent_type", "langgraph"),
        tools=json.dumps(config.get("tools", [])),
        is_active=False
    )
    
    db.add(new_config)
    db.commit()
    db.refresh(new_config)
    return new_config.to_dict()

@router.put("/{config_id}", response_model=Dict[str, Any])
def update_config(config_id: str, config_data: Dict[str, Any], db: Session = Depends(get_db)):
    """更新配置"""
    config = db.query(AgentConfig).filter(AgentConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
        
    if "name" in config_data:
        existing = db.query(AgentConfig).filter(AgentConfig.name == config_data["name"], AgentConfig.id != config_id).first()
        if existing:
            raise HTTPException(status_code=400, detail="该名称已存在")
        config.name = config_data["name"]
        
    if "description" in config_data:
        config.description = config_data["description"]
    if "system_prompt" in config_data:
        config.system_prompt = config_data["system_prompt"]
    if "model" in config_data:
        config.model = config_data["model"]
    if "agent_type" in config_data:
        config.agent_type = config_data["agent_type"]
    if "tools" in config_data:
        config.tools = json.dumps(config_data["tools"])
        
    db.commit()
    db.refresh(config)
    
    # 如果更新的是当前激活的配置，需要重载 Agent
    if config.is_active:
        reload_agent()
        
    return config.to_dict()

@router.delete("/{config_id}")
def delete_config(config_id: str, db: Session = Depends(get_db)):
    """删除配置"""
    config = db.query(AgentConfig).filter(AgentConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
        
    if config.is_active:
        raise HTTPException(status_code=400, detail="不能删除当前激活的配置")
        
    db.delete(config)
    db.commit()
    return {"message": "删除成功"}

@router.post("/{config_id}/activate")
def activate_config(config_id: str, db: Session = Depends(get_db)):
    """激活配置"""
    config = db.query(AgentConfig).filter(AgentConfig.id == config_id).first()
    if not config:
        raise HTTPException(status_code=404, detail="配置不存在")
        
    # 将所有配置设为非激活
    db.query(AgentConfig).update({"is_active": False})
    
    # 激活当前配置
    config.is_active = True
    db.commit()
    
    # 重载 Agent
    reload_agent()
    
    return {"message": f"已切换到配置: {config.name}"}
